/*
 * 文件名：LawcaseInfoController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年3月31日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.la.web;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.la.domain.LawcaseInfoAssist;
import top.infopub.mgr.la.domain.LawcaseInfoDomain;
import top.infopub.mgr.la.service.CarryLawcaseService;
import top.infopub.mgr.la.service.LawcaseInfoService;
import top.infopub.mgr.la.service.PeaceLawcaseService;
import top.infopub.mgr.la.service.SueLawcaseService;
import top.infopub.mgr.la.service.UpwardLawcaseService;
import top.infopub.mgr.la.vo.CarryLawcaseVo;
import top.infopub.mgr.la.vo.LawcaseInfoVo;
import top.infopub.mgr.la.vo.PeaceLawcaseVo;
import top.infopub.mgr.la.vo.SueLawcaseVo;
import top.infopub.mgr.la.vo.UpwardLawcaseVo;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.la.CarryLawcase;
import top.infopub.model.la.LawcaseInfoAtt;
import top.infopub.model.la.LawcaseInfoMulti;
import top.infopub.model.la.PeaceLawcase;
import top.infopub.model.la.SueLawcase;
import top.infopub.model.la.UpwardLawcase;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * 诉讼-仲裁案件信息
 * @author WuZhiyang
 * @version 2020年3月31日
 * @see LawcaseInfoController
 * @since
 */
@Controller
@RequestMapping("/lawcaseInfo")
public class LawcaseInfoController extends GenericFlowController {

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private SueLawcaseService sueLawcaseService;

    @Autowired
    private UpwardLawcaseService upwardLawcaseService;

    @Autowired
    private CarryLawcaseService carryLawcaseService;

    @Autowired
    private LawcaseInfoService lawcaseInfoService;

    @Autowired
    private PeaceLawcaseService peaceLawcaseService;

    /**
     * 诉讼-仲裁案件信息列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "la/lay-lawcaseInfo-list";
    }

    /**
     * 诉讼-仲裁案件信息列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<LawcaseInfoDomain> queryDataByCondition(LawcaseInfoVo lawcaseInfoVo,
                                                         ParamPage paramPage) {
        Page<LawcaseInfoDomain> page = new Page<LawcaseInfoDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (lawcaseInfoVo.getEndDate() != null) {
            lawcaseInfoVo.setEndDate(DateUtils.addDays(lawcaseInfoVo.getEndDate(), 1));
        }
        page = lawcaseInfoService.selectByDomainWhere(page, lawcaseInfoVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 诉讼-仲裁案件信息-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        return "la/lay-lawcaseInfo-add";
    }

    /**
     * 根据id查询诉讼-仲裁案件信息详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 诉讼-仲裁案件信息Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        LawcaseInfoVo lawcaseInfoVo = lawcaseInfoService.queryById(id);
        //request.setAttribute("modelDetail", lawcaseInfoVo);
        map.put("lawcaseInfoVo", lawcaseInfoVo);
        // 审批flag
        //request.setAttribute("processDealWith", processDealWith);
        // 审批data
        //processData(request, lawcaseInfoVo.getProcessId());
        return new ModelAndView("la/lay-lawcaseInfo-detail", map);
    }

    /**
     * 新增诉讼-仲裁案件信息
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(LawcaseInfoAssist lawcaseInfoAssist) {

        if (lawcaseInfoAssist.getFileAtts1() == null
            || lawcaseInfoAssist.getFileAtts1().length < 1) {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("案件办理思路、方案、措施未上传");
        }

        //诉讼-仲裁案件信息处理
        lawcaseInfoAssist.setHrDeptId(lawcaseInfoAssist.getHrDeptid());
        lawcaseInfoAssist.setHrOrgId(lawcaseInfoAssist.getHrOrgid());
        lawcaseInfoAssist.setHrStaffApplyId(lawcaseInfoAssist.getHrStaffApplyid());
        String proCodeAndCodes = lawcaseInfoAssist.getProCodeAndCodes();
        String[] split = proCodeAndCodes.split("\\_");
        lawcaseInfoAssist.setLawcaseName(split[0]);
        lawcaseInfoAssist.setRefLawcaseId(split[1]);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        lawcaseInfoAssist.setId(id);
        lawcaseInfoAssist.setAddBy(vo.getId());
        lawcaseInfoAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("la_lawcase_info");
        lawcaseInfoAssist.setCodes(code);
        lawcaseInfoAssist.setUptBy(vo.getId());
        lawcaseInfoAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //诉讼仲裁案件多方信息
        List<LawcaseInfoMulti> lawcaseInfoMultis = new ArrayList<LawcaseInfoMulti>();
        String[] partakeTypeInfos = lawcaseInfoAssist.getPartakeTypeInfos();
        if (partakeTypeInfos != null && partakeTypeInfos.length > 0) {
            for (int i = 0; i < partakeTypeInfos.length; i++ ) {
                String partakeType = partakeTypeInfos[i];
                String partakeInfo = lawcaseInfoAssist.getPartakeInfos()[i];
                String partakeTel = lawcaseInfoAssist.getPartakeTelInfos()[i];
                if (StringUtils.isEmpty(partakeInfo) && StringUtils.isEmpty(partakeTel)) {
                    continue;
                }
                LawcaseInfoMulti lawcaseInfoMulti = new LawcaseInfoMulti();
                String lawcaseInfoMultiId = IdFactory.getUUIDUpper();
                lawcaseInfoMulti.setLawcaseInfoId(id);
                lawcaseInfoMulti.setId(lawcaseInfoMultiId);
                lawcaseInfoMulti.setPartakeType(partakeType);
                lawcaseInfoMulti.setPartakeInfo(partakeInfo);
                lawcaseInfoMulti.setPartakeTel(partakeTel);
                lawcaseInfoMulti.setAddBy(vo.getId());
                lawcaseInfoMulti.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                lawcaseInfoMultis.add(lawcaseInfoMulti);
            }
        }

        //上传附件
        List<LawcaseInfoAtt> lawcaseInfoAtts = new ArrayList<LawcaseInfoAtt>();
        String[] fileAtts1 = lawcaseInfoAssist.getFileAtts1();
        //01=案件办理思路、方案、措施 
        if (fileAtts1 != null) {
            for (String file : fileAtts1) {
                LawcaseInfoAtt lawcaseInfoAtt = createFileAtt(vo, id, file);
                lawcaseInfoAtt.setTypes("01");
                lawcaseInfoAtts.add(lawcaseInfoAtt);
            }
        }

        String[] fileAtts2 = lawcaseInfoAssist.getFileAtts2();
        //02=其他附件
        if (fileAtts2 != null) {
            for (String file : fileAtts2) {
                LawcaseInfoAtt lawcaseInfoAtt = createFileAtt(vo, id, file);
                lawcaseInfoAtt.setTypes("02");
                lawcaseInfoAtts.add(lawcaseInfoAtt);
            }
        }

        lawcaseInfoService.saveLawcaseInfo(lawcaseInfoAssist, lawcaseInfoMultis, lawcaseInfoAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD,
            "法务管理 -诉讼-仲裁案件信息：案件名称=" + lawcaseInfoAssist.getLawcaseName(), null);
        return RspVo.getSuccessResponse();
    }

    private LawcaseInfoAtt createFileAtt(AuthorizationVO vo, String lawcaseInfoId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        LawcaseInfoAtt fileAtt = new LawcaseInfoAtt();
        fileAtt.setId(fileAttStr[2]);
        fileAtt.setLawcaseInfoId(lawcaseInfoId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "lawcaseInfoAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据类型查询对应的案件记录
     * @param type 原申请单类型 01=起诉案件,02=上诉案件,03=执行案件,04=调解案件
     * @return
     * @throws Exception
     */
    @RequestMapping("/getLawcaseByType")
    @ResponseBody
    public Map<String, Object> getLawcaseByType(String lawcaseType) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            //前端传来的原申请单类型 lawcaseType
            if ("01".equals(lawcaseType)) {
                SueLawcase sueLawcase = new SueLawcase();
                sueLawcase.setProcessStatus("9");
                List<SueLawcase> sueLawcases = sueLawcaseService.selectByEntityWhere(sueLawcase);
                map.put("lawcases", sueLawcases);
            }
            else if ("02".equals(lawcaseType)) {
                UpwardLawcase upwardLawcase = new UpwardLawcase();
                upwardLawcase.setProcessStatus("9");
                List<UpwardLawcase> upwardLawcases = upwardLawcaseService.selectByEntityWhere(upwardLawcase);
                map.put("lawcases", upwardLawcases);
            }
            else if ("03".equals(lawcaseType)) {
                CarryLawcase carryLawcase = new CarryLawcase();
                carryLawcase.setProcessStatus("9");
                List<CarryLawcase> carryLawcases = carryLawcaseService.selectByEntityWhere(carryLawcase);
                map.put("lawcases", carryLawcases);
            }
            else if ("04".equals(lawcaseType)) {
                PeaceLawcase peaceLawcase = new PeaceLawcase();
                peaceLawcase.setProcessStatus("9");
                List<PeaceLawcase> peaceLawcases = peaceLawcaseService.selectByEntityWhere(peaceLawcase);
                map.put("lawcases", peaceLawcases);
            }
        }
        catch (Exception e) {
            log.error("根据类型查询案件记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据id查询起诉、上诉、执行、和解案件记录
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getLawcaseInfoById")
    @ResponseBody
    public Map<String, Object> getLawcaseInfoById(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String proCodeAndCodes = request.getParameter("proCodeAndCodes");
            String lawcaseType = request.getParameter("lawcaseType");
            String[] split = proCodeAndCodes.split("\\_");
            if ("01".equals(lawcaseType)) {
                SueLawcaseVo sueLawcaseVo = sueLawcaseService.queryById(split[1]);
                map.put("lawcaseVo", sueLawcaseVo);
            }
            else if ("02".equals(lawcaseType)) {
                UpwardLawcaseVo upwardLawcaseVo = upwardLawcaseService.queryById(split[1]);
                map.put("lawcaseVo", upwardLawcaseVo);
            }
            else if ("03".equals(lawcaseType)) {
                CarryLawcaseVo carryLawcaseVo = carryLawcaseService.queryById(split[1]);
                map.put("lawcaseVo", carryLawcaseVo);
            }
            else if ("04".equals(lawcaseType)) {
                PeaceLawcaseVo peaceLawcaseVo = peaceLawcaseService.queryById(split[1]);
                map.put("lawcaseVo", peaceLawcaseVo);
            }
        }
        catch (Exception e) {
            log.error("查询起诉、上诉、执行、和解案件记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

}